<template>
  <div class="category-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>IP分类列表</span>
          <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="categoryList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button
                type="primary"
                link
                @click="handleStatusChange(row)"
              >{{ row.status === 'active' ? '禁用' : '启用' }}</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据
const mockCategories = [
  {
    id: 1,
    name: '动漫IP',
    description: '日本动漫相关IP授权',
    status: 'active',
    createTime: '2024-01-01T00:00:00Z'
  },
  {
    id: 2,
    name: '游戏IP',
    description: '知名游戏IP授权',
    status: 'active',
    createTime: '2024-01-02T00:00:00Z'
  },
  {
    id: 3,
    name: '影视IP',
    description: '电影电视剧IP授权',
    status: 'inactive',
    createTime: '2024-01-03T00:00:00Z'
  }
]

const loading = ref(false)
const categoryList = ref(mockCategories)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const form = ref({
  name: '',
  description: '',
  status: 'active'
})

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入分类描述', trigger: 'blur' },
    { max: 200, message: '最多200个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const getList = async () => {
  loading.value = true
  try {
    // 这里应该是API调用，现在使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    categoryList.value = mockCategories
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增分类
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    description: '',
    status: 'active'
  }
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 模拟新增
          const newCategory = {
            ...form.value,
            id: categoryList.value.length + 1,
            createTime: new Date().toISOString()
          }
          categoryList.value.push(newCategory)
          ElMessage.success('新增成功')
        } else {
          // 模拟编辑
          const index = categoryList.value.findIndex(item => item.id === form.value.id)
          if (index !== -1) {
            categoryList.value[index] = { ...categoryList.value[index], ...form.value }
            ElMessage.success('编辑成功')
          }
        }
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 修改状态
const handleStatusChange = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    const index = categoryList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      categoryList.value[index].status = newStatus
      ElMessage.success(`${newStatus === 'active' ? '启用' : '禁用'}成功`)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      type: 'warning'
    })
    const index = categoryList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      categoryList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 